<%@ page contentType="text/html; charset=utf-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<%@include file="/static/common/header.jsp"%>
<%@include file="/static/common/easyui.jsp"%>
<%@include file="/static/common/common.jsp"%>
<link href="${ctx}/static/css/main.css" rel="stylesheet">
<script>  

$(document).ready(function(){
	$('#roleTable').datagrid({
		title:'角色查询',
		iconCls:'icon-bumen',
		method:'POST',
		width:665,
		height:450,
		nowrap: false,
		striped: true,
		collapsible:false,
		url: '${ctx}/Mng/role/list',
		idField:'id',
		columns:[[
			{field:'roleName',title:'角色名称',width:120},
			{field:'roleDesp',title:'角色描述',width:200},
			{field:'available',title:'是否有效',width:80},
			{field:'orgNameCn',title:'所属机构',width:120},
			{field:'id',title:'操作',width:100,rowspan:2,formatter:function(value, row, index){
						return '<a href="#" style="color:blue" onClick="initRoleAuthState(\''+row.id+'\',\''+row.roleName+'\')">[ 分配权限 ]</a>'; 
			}},
		]],
		pagination:true,
		pageSize:10,
		rownumbers:true,
		
		toolbar:'#tb',
		onLoadSuccess:function(){
			$('#roleTable').datagrid('clearSelections'); //一定要加上这一句，要不然datagrid会记住之前的选择状态，删除时会出问题
		}
	});
	
});

function initRoleAuthState(_id,_roleName){
	 
	 $("#sysMenuLayout").panel({title:_roleName+" : 可用功能"});
	 $("#rid").val(_id);
	 checkRoleMenu(_id);
	 hiddenOpt('show'); 
}
	
	//+'&stmp='+(new Date()).getTime()
function checkRoleMenu(id)
{
		  var node = '';
		  $.ajax({
			type: 'get',
			url : '${ctx}/Mng/role/getRoleMenus/'+id+'/stmp='+(new Date()).getTime(),
			success : function(data) {
			 var nodes = $('#menuTreeObj').tree('getChildren');
							for(var i=0; i<nodes.length; i++){
								$('#menuTreeObj').tree('uncheck', nodes[i].target);
			}
				
			var jsonlist = data.rmenus;
				$.each(jsonlist,function(i, n){
					node = $('#menuTreeObj').tree('find', n);
					if(node)
						$('#menuTreeObj').tree('check', node.target);
				});
				 
			}

		});
}
	
//新增
function addrow(){
	showWin(function() {
		$('#roleForm').form('clear');
	});
	hiddenOpt()
}

function hiddenOpt(opt){
	if(opt=='show'){
	$('#roleMainLayout').layout('expand','east'); 
	}else
	$('#roleMainLayout').layout('collapse','east'); 
}

function showWin(onLoad) {
	$("#MyPopWindow").window({
		title:'增加角色信息',
		href:'${ctx}/Mng/role/addWin?opt=N',
		width:550,
		height:500,
		onLoad: onLoad
	});
}

function showWin2(onLoad) {
	$("#MyPopWindow").window({
		title:'更新角色信息',
		href:'${ctx}/Mng/role/addWin?opt=E',
		width:550,
		height:500,
		onLoad: onLoad
	});
}
//更新
function updaterow(data){
	if(data == null) {
		var rows = $('#roleTable').datagrid('getSelections');
		//这里有一个jquery easyui datagrid的一个小bug，必须把主键单独列出来，要不然不能多选
		if(rows.length==0){
			showInfo("请选择一条数据",'info');
			return;
		}
		showWin2(function() {
			$("#roleForm").form('load', rows[0]);
		});
	} else {
		showWin2(function() {
			$("#flightForm").form('load', data);
		});
	}
	hiddenOpt();
}

function addOrUpdateRole(opt){
	var r = $('#roleForm').form('validate');
	if(!r) {
		return false;
	}
	var url = '${ctx}/Mng/role/addOrUpdate?opt='+opt;
	$.postJSON(
		url,
		$("#roleForm").serializeObject(),
		function(data) {
			if (data && data.success == "true") {
				$('#MyPopWindow').window('close');
				$('#roleTable').datagrid('reload');  
				if("E"==opt){
					showInfo("数据更新成功")
				}else{
					showInfo("数据添加成功")
				}
			} else if(data.check_name == "false"){
				showInfo('角色名称重复');
			} else {
				showInfo('服务器繁忙，请稍候重试！');
			}
		}
	);	
}

	
//删除
function deleteRow(){
		var rows = $('#roleTable').datagrid('getSelections');
		if(rows.length==0){
			$.messager.alert('提示',"请选择你要删除的数据",'info');
			return;
		}
		$.messager.confirm('提示','确定要删除吗?',function(result){
        if (result){
			hiddenOpt();
        	var ps = "";
        	$.each(rows,function(i,n){
        		if(i==0) 
        			ps += "/"+n.id;
        		else
        			ps += ","+n.id;
        	});
        	$.ajax({
				type: 'get',
				url : '${ctx}/Mng/role/delete' + ps+'?stmp='+(new Date()).getTime(),
				beforeSend:function(){
					$("body").mask("正在处理中...");
        		},
			    success: function(data) {
        			$("body").unmask();
        			if (data && data.success == "true") {
                    	$('#roleTable').datagrid('reload');  
            		} else {
            			if(data.check_name =="false")
            				{
            				 showInfo('角色名已存在，请重试！','error');
            				}
            			else
            				{
            				 showInfoCenter(data.err_msg+' 请稍候重试！','error');
            				}
            			    
            		}
			    }
			});
        	
        }
    });
}
//表格查询
function searchRole(){
	hiddenOpt();
	var params = $('#roleTable').datagrid('options').queryParams; //先取得 datagrid 的查询参数
	var fields =$('#queryForm').serializeArray(); //自动序列化表单元素为JSON对象
	
	$.each( fields, function(i, field){
		params[field.name] = field.value; //设置查询参数
	}); 
	
	$('#roleTable').datagrid('reload'); //设置好查询参数 reload 一下就可以了
}
//清空查询条件
function clearForm(){
	$('#queryForm').form('clear');
	searchRole();
}


	
	
	function checkInArray(str,arr){
	   str +='';
	   var ar = arr.split(',');
	   var f = $.inArray(str, ar); 
	   if(f==-1)
	   {
		  return false;   
	   }
	   else
	   {
		  return true;   
	   }
   }
	
	function loadMenuOptButGridData(node){
		var curId=node.id;
		$('#pmid').val(curId);
		   var nodes = $('#menuTreeObj').tree('getChecked');
			for(var i=0; i<nodes.length; i++){
				if(nodes[i].id==curId)
				{
					initOpernGridData('${ctx}/Mng/Menu/operateGridData?menuId='+curId);
				}
							
			}
		  
	}

	function initOpernGridData(_url){
		$('#menuOptButGridData').datagrid({
			url:_url,
			iconCls:'icon-bumen',
			method:'post', fit:true,
			nowrap: false,
			striped: true,
			collapsible:false, 
			idField:'id',
			onCheck:function (rowIndex,rowData){
			    updateAuthOpt(null);       
			},
			onUncheck:function (rowIndex,rowData){
			     updateAuthOpt(rowData);  
			},
			onLoadSuccess:checkRoleOpts,
			columns:[[
				{field:'ck',checkbox:true},
				{field:'id',title:'',hidden:'true'},
				{field:'menuId',title:'',hidden:'true'},
				{field:'name',title:'名称',width:80}//,{field:'code',title:'代码',width:120}
			]],
			rownumbers:true
		});
	}
	function getChecked(){
		var nodes = $('#menuTreeObj').tree('getChecked');
		var s = '0';
		for(var i=0; i<nodes.length; i++){
			if (s != '') s += ',';
			s += nodes[i].id;
		}
		return s;
	}
	
	function saveAuthMenu(){
		 var id =  $("#rid").val();
		 if(id!=''){ 
			$.ajax({
					type: 'get',
					url : "${ctx}/Mng/role/updateRoleAuthority/"+$("#rid").val()+"/"+getChecked()+'/stmp='+(new Date()).getTime(),
					success: function(data) {
					  if (data && data.success == "true") {
						 showInfo();
					  }else
					  {
						  showInfo('服务器繁忙，请稍候重试！');
					  }
						 
					}
	
			});
		}
	}
	
	function setUpOrgInfo(){
		openWin3("orgSelectWin","机构选取 >> 双击选取");
	}
	
	function setSelOrgNode(node){
		if(node){
			$("#orgId").val(node.id);
			$("#orgCode").val(node.orgCode);
			$("#orgNameCn").val(node.text);
			$('#orgSelectWin').window('close');
		}else{
			showInfoCenter("未选取机构！");
		}
	}
</script>
</head>
<body id="roleMainLayout" class="easyui-layout" >
	<div region="center" class="bmargin">
		<table id="roleTable" data-options="singleSelect:true,fit:true">
		</table>
	</div>
	
	<div id="sysMenuLayout" data-options="region:'east',split:true,collapsed:true,title:'权限',Toolbar:'#authToolbar'" style="width:460px;">
		<input type="hidden" id="rid"/>
		<input type="hidden" id="pmid"/>
  		<!-- menu -->
		<div id="authToolbar" class="datagrid-toolbar" style=" text-align:right">
	   		<a href="javascript:void(0)" onClick="saveAuthMenu();" id="btnAuthSave" class="easyui-linkbutton" iconCls="icon-save" plain="true">保存</a> 
		</div>
      	<ul class="easyui-tree" id="menuTreeObj" data-options="url:'${ctx}/Mng/Menu/treeData',animate:true,checkbox:true"></ul>
  		<!-- menu -->
	</div>

	<div id="tb" class="datagrid-toolbar" style="padding:5px;height:auto">
		<div style="margin-bottom:5px">
    		<form id="queryForm">
      			角色名:<input type="text" name="roleName" id="rname" style="width:100px">
    		</form>
		</div>
		<div>
			<a href="javascript:void(0)" onClick="addrow();" id="btnadd" class="easyui-linkbutton" iconCls="icon-add" plain="true">添加</a>
			<a href="javascript:void(0)" onClick="deleteRow();" id="btnremove" class="easyui-linkbutton" iconCls="icon-remove" plain="true">删除</a>
			<a href="javascript:void(0)" onClick="updaterow(null);" id="btnedit" class="easyui-linkbutton" iconCls="icon-edit" plain="true">更新</a>
			<span style="float:right">
				<a href="javascript:void(0)" onClick="searchRole();" class="easyui-linkbutton" iconCls="icon-search">搜索</a>
				<a href="javascript:void(0)" onClick="clearForm();" class="easyui-linkbutton" iconCls="icon-reload">清空</a>
			</span> 
		</div>
	</div>

	<div id="MyPopWindow" modal="true" shadow="false" minimizable="false" cache="false" maximizable="false" collapsible="false" resizable="false" style="margin: 0px;padding: 0px;overflow: auto;"></div>
	
	<div id="orgSelectWin" class="easyui-window" data-options="modal:true,closed:true,iconCls:'icon-edit',title:'机构'" style="width:560px;height:460px;padding:10px;">
		<ul id="orgTreeObject" class="easyui-tree" data-options="url:'${ctx}/Mng/org/treeGridData',animate:true,dnd:true,onDblClick:function(node){setSelOrgNode(node);}">
		</ul>
	</div>

</body>
</html>
